package com.virus.server.servlet;

import com.virus.server.catalina.Context;
import com.virus.server.http.Request;
import com.virus.server.http.Response;
import com.virus.server.utils.FileUtils;
import com.virus.server.utils.ServerXmlUtils;
import com.virus.server.utils.WebXmlUtils;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

public class DefaultServlet extends GenericServlet {

    public static DefaultServlet INSTANCE = new DefaultServlet();

    private Map<String, Context> contextMap;

    private DefaultServlet() {
        contextMap = ServerXmlUtils.getContextMap();
    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        Request request = (Request) servletRequest;
        Response response = (Response) servletResponse;
        String servletPath = request.getServletPath();
        String contextPath = request.getContextPath();
        if (servletPath.contains(".")) {
            int i = servletPath.lastIndexOf(".");
            String extension = servletPath.substring(i + 1);
            String mineType = WebXmlUtils.getMineType(extension);
            response.setContentType(mineType);
        }
        Set<String> keySet = contextMap.keySet();
        File file = new File("");
        for (String key : keySet) {
            Context context = contextMap.get(key);
            if (key.equals(contextPath) && (servletPath.isEmpty() || servletPath.equals("/"))) {
                String welcomeFile = WebXmlUtils.getWelcomeFile(context);
                file = new File(welcomeFile);
                break;
            }
            if (key.equals(contextPath)) {
                file = new File(context.getDocBose() + servletPath);
                break;
            }
        }
        if (file.exists() && !file.isDirectory()) {
            byte[] bytes = FileUtils.getBytes(file);
            response.setResponseBody(bytes);
            return;
        }
        response.setStatus(404);
        response.getWriter().println("File Not Found");
    }
}
